/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Codec;

import PIServer.Main;
import Message.Message;
import java.nio.ByteBuffer;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

/**
 *
 ** @author Nhan Nguyen
 */
class MessageRequestEncoder implements ProtocolEncoder {

    public static MessageRequestEncoder getInstance() {
        return InstanceHolder.INSTANCE;
    }

    private static final class InstanceHolder {

        private static final MessageRequestEncoder INSTANCE = new MessageRequestEncoder();
    }

//    public static long packet = 0;
//    public static long times = 0;
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        try {
            Message msg = (Message) message;
            int buflen = msg.getBuffer().getLength();

            //log.info("- Encoded: length=" + buflen
            //        + ", Service Type=" + msg.getActionCommand() + ", Command Type=" + msg.getServiceType());

            IoBuffer buffer = IoBuffer.allocate(12, false);
            buffer.setAutoExpand(true);

            buffer.putInt(buflen + 8);
            buffer.putInt(msg.getActionCommand());
            buffer.putInt(msg.getServiceType());

            if (buflen > 0) {
                byte[] bufdata = new byte[buflen];
                System.arraycopy(msg.getBuffer().getData(), 0, bufdata, 0, buflen);
                buffer.put(bufdata);
            }

            buffer.flip();
            out.write(buffer);

//            if (System.currentTimeMillis() > times) {
//                times = System.currentTimeMillis() + 30 * 1000;
//                System.out.println("Packet delivered: "+packet);
//                packet = 0;
//            }
//            packet++;

        } catch (Exception ex) {
            Main.log.error("Message Encoder Exception", ex);
        }
    }

    public void dispose(IoSession is) throws Exception {
    }
}
